<?php

namespace App\Supports\Payment\Methods\Wxpay;

use Exception;
use App\Supports\Payment\Methods\Method;
use Illuminate\Validation\ValidationException;
use App\Supports\Payment\Contracts\MethodRefund;

class RefundOrder extends Method implements MethodRefund
{
	public function validate($refund = null)
	{
		if (! $refund->order->isPaid()) {
			abort(403, '目标订单未支付');
		}
		if ($refund->order->isClosed()) {
			abort(403, '目标订单已关闭');
		}
		if ($refund->order->isCancelled()) {
			abort(403, '目标订单已取消');
		}
		if ($refund->order->has_refund) {
			abort(403, '目标商品已退款');
		}
		if ($refund->order->paid_method !== 'wxpay') {
			abort(403, '目标订单不能通过微信支付退款');
		}
		if ($refund->refund_status !== 'confirmed') {
			abort(403, '目标售后未审核');
		}
	}
	
	public function info($refund = null)
	{
		$outTradeNo = 'order_'.$refund->order->number;
		$totalFee = $refund->order->total_amount * 100;
		$refundFee = $refund->refund_money * 100;
		
		$refund->update(['refund_status' => 'processing']);
		
		return [
			'out_trade_no' => $outTradeNo,
			'out_refund_no' => $refund->refund_number,
			'total_fee' => $totalFee,
			'refund_fee' => $refundFee,
			'notify_url' => route('web.payments.wxpay.refund.notify')
		];
	}
	
	public function refund($refund = null)
	{
		$this->validate($refund);
		
		try {
			$info = $this->info($refund);
			return $this->channel->refund($info);
		} catch (Exception $exception) {
			throw ValidationException::withMessages(['err' => '支付暂不可用!']);
		}
	}
}
